<template>
  <div class="app-container">
    <!-- 顶部功能 -->
    <div class="filter-container" style="margin-bottom: 15px">
      <!-- 用户名输入 -->
      <el-input v-model="queryParam.userName" placeholder="用户名" style="width: 200px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- 一些按钮 -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleShowAll">
        显示全部
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加用户
      </el-button>
      <el-upload class="filter-item" action="" :on-change="fileonChange" :auto-upload="false" :show-file-list="false"
        multiple>
        <el-button style="margin-left: 10px" type="primary" icon="el-icon-folder-add">
          导入用户
        </el-button>
      </el-upload>
      <el-button class="filter-item" style="margin-left: 10px" type="danger" icon="el-icon-delete"
        @click="handleDeleteSome">
        批量删除
      </el-button>
    </div>

    <!--弹出框-->
    <!-- :close-on-click-modal="false" -->
    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="40%">
      <el-row>
        <el-col :span="16">
          <!--普通表单-->
          <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="姓名" prop="name">
              <template v-if="formType == 0">
                <el-input v-model="form.name" />
              </template>
              <template v-else>
                <span>{{ form.name }}</span>
              </template>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <template v-if="formType == 0">
                <el-input v-model="form.userName" />
              </template>
              <template v-else>
                <span>{{ form.userName }}</span>
              </template>
            </el-form-item>
            <el-form-item v-if="formType == 0" label="密码" prop="password">
              <el-input v-model="form.password" />
            </el-form-item>
            <el-form-item v-if="formType == 1" label="剩余时长" prop="endTime">
              <span>{{ form.endTime }}分钟</span>
            </el-form-item>
            <el-form-item label="登录时长" prop="duration">
              <el-input v-model="form.duration" style="max-width: 600px" placeholder="登录时长">
                <template #append>小时</template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--数据表格-->
    <el-table ref="multipleTable" :data="tableData" border>

      <el-table-column type="selection" width="55" fixed align="center" />

      <el-table-column prop="id" label="序号" align="center" width="100" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="剩余时长（分钟）" align="center" prop="duration" />
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="resetPw(scope.row)">重置密码</el-button>
          <el-button :disabled="id !== 1" type="primary" size="small" @click="handleUpdate(scope.row)">增加时长</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页条-->
    <el-pagination background :current-page.sync="queryParam.pageNum" :page-sizes="[5, 10, 20, 50]"
      :page-size="queryParam.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="recordTotal"
      style="margin-top: 15px" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import waves from '@/directive/waves' // waves directive
import {
  queryUsersByPage,
  addUser,
  deleteUser,
  deleteUsers,
  updateDuration,
  uploadUser,
  updateUser
} from '@/api/admin/user'

export default {
  name: 'UserList',
  directives: { waves },
  data() {
    return {
      // 表格数据
      tableData: [],
      // 记录总数
      recordTotal: 0,
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userName: null
      },
      // 对话框表单显示
      dialogFormVisible: false,
      // 表单类型（添加数据:0,修改数据:1）
      formType: 0,
      // 表单数据
      form: {
        id: null,
        userName: null,
        password: null,
        name: null,
        duration: null,
        endTime: null,
        adminId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入登录时长', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 获得user信息
    ...mapGetters(['id', 'name', 'roles']),
    // 通过表单类型计算表单标题
    formTitle() {
      return this.formType === 0 ? '添加用户' : '增加时长'
    }
  },
  // 创建后
  created() {
    // 从服务器获取数据表格第一页的信息
    // 默认page=1，size=10
    this.queryPage()
  },
  methods: {
    // 重置密码
    resetPw(row) {
      const data = {
        id: row.id,
        password: '123456'
      }
      updateUser(data).then(res => {
        if (res.status === 200) {
          this.$message.success('重置密码成功')
        } else {
          this.$message.error('重置密码失败')
        }
      })
    },
    // 文件导入
    fileonChange(file) {
      const formData = new FormData()
      formData.append('file', file.raw)
      uploadUser(formData).then((res) => {
        this.handleCurrentChange(this.queryParam.pageNum)
        this.$message.success('导入成功')
      })
    },
    // 查询分页
    queryPage() {
      queryUsersByPage(this.queryParam).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.rows
          this.recordTotal = res.data.total
        }
      })
    },

    // 分页大小改变监听
    handleSizeChange(curSize) {
      this.queryParam.pageSize = curSize
      this.queryPage()
    },

    // 点击分页监听方法
    handleCurrentChange(curPage) {
      this.queryParam.pageNum = curPage
      this.queryPage()
    },

    // 搜索
    handleFilter() {
      this.queryParam.pageNum = 1
      this.queryPage()
    },

    // 点击显示全部
    handleShowAll() {
      this.queryParam.pageNum = 1
      this.queryParam.userName = null
      this.queryPage()
    },

    // 点击添加记录
    handleCreate() {
      // 表单是添加状态
      this.formType = 0
      // 将空数据置入form
      this.form = {
        id: null,
        name: null,
        userName: null,
        password: null,
        duration: null,
        endTime: null
      }
      // 显示表单框
      this.dialogFormVisible = true
    },

    // 点击修改记录
    handleUpdate(row) {
      // 表单是修改状态
      this.formType = 1
      // 将行数据置入form
      this.form = {
        id: row.id,
        userName: row.userName,
        password: row.password,
        name: row.name,
        duration: null,
        endTime: row.duration
      }
      // 显示表单框
      this.dialogFormVisible = true
    },

    // 添加和更新的提交表单
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message.error('不允许提交，请检查必填项')
          return false
        }
        if (this.formType === 0) {
          // 添加记录
          this.form.adminId = this.$store.state.user.id
          addUser(this.form).then((res) => {
            if (res.status === 200) {
              this.$message.success('添加记录成功')
              // 跳转到末尾
              this.handleCurrentChange(this.queryParam.pageNum)
            } else {
              if (res.status === 501) this.$message.error(res.message)
              else this.$message.error('添加记录失败')
            }
            this.dialogFormVisible = false // 关闭对话框
          })
        } else if (this.formType === 1) {
          // 增加时长
          const data = {
            duration: this.form.duration,
            id: this.form.id
          }
          updateDuration(data).then((res) => {
            if (res.status === 200) {
              this.$message.success('增加时长成功')
              this.queryPage()
              this.dialogFormVisible = false // 关闭对话框
            } else {
              if (res.status === 501) this.$message.error(res.message)
              else this.$message.error('增加时长失败')
            }
          })
        }
      })
    },

    // 删除记录
    handleDelete(row, index) {
      this.$confirm('确定要删除该条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then((res) => {
          if (res.status === 200) {
            this.$message.success('删除记录成功')
            this.tableData.splice(index, 1)
            // 如果删完了，获取上一页
            if (this.tableData.length === 0) {
              this.queryParam.pageNum = this.queryParam.pageNum - 1
              this.handleCurrentChange(this.queryParam.pageNum)
            }
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },

    // 删除一些
    handleDeleteSome() {
      // 获取选中的对象数组
      const items = this.$refs.multipleTable.selection
      if (items.length === 0) {
        this.$message.error('至少选择一条记录')
        return
      }
      this.$confirm('确定要删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idList = []
        items.forEach(element => {
          idList.push(element.id)
        })
        const ids = idList.join(',')
        deleteUsers({ ids }).then((res) => {
          if (res.status === 200) {
            this.$message.success('批量删除记录成功')
            if (this.tableData.length === items.length) {
              // 如果本页内容全部删光了
              // 当前页为上一页
              if (this.queryParam.pageNum !== 0) {
                this.queryParam.pageNum = this.queryParam.pageNum - 1
              }
            }
          } else {
            this.$message.error(res.message)
          }
          // 重载当前页
          this.handleCurrentChange(this.queryParam.pageNum)
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-item {
  display: inline-block;
}
</style>
